const http = require("http");
const url = require("url");
const fs = require("fs");
const qs = require("querystring");

const server = http.createServer((req, res) => {
  const { pathname, query } = url.parse(req.url);

  if (pathname === "/upload" && req.method === "POST") {
    req.setEncoding("binary");

    let body = "";
    const totalBoundary = req.headers["content-type"].split(";")[1];
    const boundary = totalBoundary.split("=")[1];

    req.on("data", (data) => {
      // body = body + data;
      body += data;
    });

    res.on("end", () => {
      // 处理body
      console.log(body);

      // 获取image/png的位置
      const payload = qs.parse(body, "\r\n", ": ");
      const type = payload["Content-Type"];

      // 开始在image/png的位置进行截取
      const typeIndex = body.indexOf(type);
      const typeLength = type.length;
      let imageData = body.substring(typeIndex + typeLength);

      // 将中间的两个空格去掉
      imagedata = imageData.replace(/^\s\s*/, "");

      // 将最后的boundary去掉
      imageData = imageData.substring(0, imageData.indexOf(`--${boundary}--`));

      fs.writeFile("./foo.png", imageData, "binary", (err) => {
        console.log("文件上传成功");
        res.end("文件上传成功");
      });
    });
  }
});

server.listen(8000, () => {
  console.log("文件上传服务器开启成功");
});
